#include "recordwidget.h"
#include "ui_recordwidget.h"
#include "database/dbtabbase.h"
#include "database/dbtabrecordhlo.h"
#include "database/dbtabrecordclass.h"
#include "common/common.h"
#include "dataview/recordhlomodel.h"
#include <QDir>

#define CHECKRECORD USB"CheckRecord"+QDateTime::currentDateTime().toString("yyyyMMddhhmmss")+".csv"
#define CLASSRECORD USB"ClassifierRecord"+QDateTime::currentDateTime().toString("yyyyMMddhhmmss")+".csv"

RecordWidget::RecordWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecordWidget)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);
    setWindowState(Qt::WindowMaximized);
    mModel = new RecordHLOModel(this);
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);
    ui->tableView->setHHeadResizeMode(QHeaderView::Stretch);
    mCurrPage = NONE;
    initTvCheck();
}

RecordWidget::~RecordWidget()
{
    delete ui;
}

void RecordWidget::setTableInfo(const QString &name, const QMap<QString, QString> mTitleMap, bool showAll)
{
    mModel->setTable(name);
    ui->tableView->setModel(mModel);
    QStringList list = DBTabBase::getColumnNameList(name,DataBase::getDataBase());
    for(int i=0,t=list.size();i<t;i++){
        if(mTitleMap.contains(list.at(i))){
            mModel->setHeaderData(i, Qt::Horizontal, mTitleMap.value(list.at(i)));
            qDebug()<<mTitleMap.value(list.at(i));
        }else{
            if(showAll)
                mModel->setHeaderData(i, Qt::Horizontal, list.at(i));
        }
    }

   //ui->tableView->verticalHeader()->setDefaultSectionSize(53);
        for(int i=0,t=list.size();i<t;i++){
            if(mTitleMap.contains(list.at(i))){
                ui->tableView->setColumnHidden(i,false);
            }else{
                ui->tableView->setColumnHidden(i,!showAll);
            }
        }
    ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:darkblue/*background-color: #7393b8*/;"
                                                     "color: white;padding-left: 8px;border: 2px solid #6c6c6c;}");
    ui->tableView->verticalHeader()->setStyleSheet("QHeaderView::section {background-color:orange}");
    ui->tableView->horizontalHeader()->setFixedHeight(40);
    //ui->tableView->horizontalScrollBar()->setStyleSheet("background-color:grey;");
    //ui->tableView->verticalScrollBar()->setStyleSheet("background-color:grey;");
}

void RecordWidget::initTvCheck()
{
    if(mCurrPage!=PAGE_CHECK)
    {   mTitleMap.clear();
        mTitleMap.insert(DBTabRecordHLO::_DATE,"日期");
        mTitleMap.insert(DBTabRecordHLO::_TIME,"时间");
        mTitleMap.insert(DBTabRecordHLO::_PRODUCT_NAME,"产品名");
        mTitleMap.insert(DBTabRecordHLO::_NET,"净重");
        mTitleMap.insert(DBTabRecordHLO::_TARE,"皮重");
        mTitleMap.insert(DBTabRecordHLO::_GROSS,"毛重");
        mTitleMap.insert(DBTabRecordHLO::_HI,"上限");
        mTitleMap.insert(DBTabRecordHLO::_OK,"标准值");
        mTitleMap.insert(DBTabRecordHLO::_LOW,"下限");
        mTitleMap.insert(DBTabRecordHLO::_CHKRESULT,"检重结果");
        mTitleMap.insert(DBTabRecordHLO::_USER,"操作员");
        setTableInfo(DBTabRecordHLO::TAB_NAME,mTitleMap);
        mCurrPage = PAGE_CHECK;
        mModel->select();
        while (mModel->canFetchMore()) {
                mModel->fetchMore();
            }
        ui->tableView->scrollToBottom();
    }
}

void RecordWidget::initTvClass()
{
    if(mCurrPage!=PAGE_CLASS)
    {
        mTitleMap.clear();
        mTitleMap.insert(DBTabRecordClass::_DATE,"日期");
        mTitleMap.insert(DBTabRecordClass::_TIME,"时间");
        mTitleMap.insert(DBTabRecordClass::_PRODUCT_NAME,"产品名");
        mTitleMap.insert(DBTabRecordClass::_NET,"净重");
        mTitleMap.insert(DBTabRecordClass::_TARE,"皮重");
        mTitleMap.insert(DBTabRecordClass::_GROSS,"毛重");
        mTitleMap.insert(DBTabRecordClass::_RANGE,"区间");
        mTitleMap.insert(DBTabRecordClass::_CHKRESULT,"检重结果");
        mTitleMap.insert(DBTabRecordClass::_USER,"操作员");
        setTableInfo(DBTabRecordClass::TAB_NAME,mTitleMap);
        mCurrPage = PAGE_CLASS;
        mModel->select();
        while (mModel->canFetchMore()) {
                mModel->fetchMore();
            }
        ui->tableView->scrollToBottom();
    }
}

void RecordWidget::on_btn_checkTab_clicked()
{
    initTvCheck();    
}

void RecordWidget::on_btn_classTab_clicked()
{
    initTvClass();
}

void RecordWidget::on_btn_back_clicked()
{
    this->deleteLater();
}

void RecordWidget::on_btn_del_clicked()
{
    auto selectModel = ui->tableView->selectionModel();
    QModelIndexList qMIndexlist = selectModel->selectedRows();
    if(qMIndexlist.isEmpty())
        return;
    auto i = qMIndexlist.end()-1;
    while(1)//从选中的最后一行开始删
    {
        mModel->removeRow(i->row());
        if(i==qMIndexlist.begin())
            break;
        else {
            i--;
        }
    }
    mModel->select();
    while (mModel->canFetchMore()) {
            mModel->fetchMore();
        }
    ui->tableView->scrollToBottom();
}

void RecordWidget::on_btn_print_clicked()
{

}

void RecordWidget::on_btn_export_clicked()
{
    QDir dir(USB);
    if(!dir.exists())
    {
        MyMessageDialog::message(0,"错误","请插入U盘!");
        return;
    }
    QFile* file;
    QStringList list ;
    if(mCurrPage == PAGE_CHECK)
    {
        list = DBTabBase::getColumnNameList(DBTabRecordHLO::TAB_NAME,DataBase::getDataBase());
        file = new QFile(CHECKRECORD);qDebug()<<file->fileName();
    }
    else if(mCurrPage == PAGE_CLASS )
    {
        list = DBTabBase::getColumnNameList(DBTabRecordClass::TAB_NAME,DataBase::getDataBase());
        file = new QFile(CLASSRECORD);qDebug()<<file->fileName();
    }
    if(!file->open(QIODevice::WriteOnly|QIODevice::Append))
    {
        qDebug()<<file->errorString();
        return;
    }

    int rowCnt = mModel->rowCount();qDebug()<<rowCnt;
    bool addedHead = false;
    for(int row = 0;row<rowCnt;row++)
    {
        QSqlRecord recd =  mModel->record(row);
        QByteArray arrLine = "";

        if(!addedHead)
        {
            for(int i=0,t=list.size();i<t;i++)
            {
                if(mTitleMap.contains(list.at(i))){
                    arrLine.append(mTitleMap.value(list.at(i)).toUtf8());
                    arrLine.append(",");
                }
            }
            arrLine.chop(1);
            arrLine.append("\r\n");qDebug()<<arrLine;
            addedHead = true;
        }

        for(int i=0,t=list.size();i<t;i++)
        {
            if(mTitleMap.contains(list.at(i))){
                arrLine.append(recd.value(i).toByteArray());
                arrLine.append(",");
            }
        }
        arrLine.chop(1);
        arrLine.append("\r\n");
        file->write(arrLine);
    }
    DoSystem("sync");
    beep1;
    file->close();
    delete file;
}

void RecordWidget::on_btn_up_clicked()
{
    ui->tableView->pageUp();    
}

void RecordWidget::on_btn_down_clicked()
{
    ui->tableView->pageDown();    
}
